// pages/Goods/Commit/index.js
var common = require("../../../public.js")
const config = require('../../../config.js')
Page({
  data: {
    isFyApp: config.isFyApp,
    selectedAddr: false,
    active: 0, //默认选中配送方式  开始根据下标0开始
    userInfo: [],
    itemId: 0,
    storeId: 0,
    cityBenefitItemFlag: false, // 市级惠民
    benefitItemFlag: false, // 省级惠民1
    storeInfo: '', //店铺详情
    goodsInfo: '', //商品详情
    totalPostType: [], //根据店铺返回的共有多少个配送方式
    postType: 1, //邮寄方式
    count: 1, //数量
    price: 0, //单价
    storePrice: '', //商品总价
    benefitCost: '', //券的金额
    totalMoney: 0, // 最后支付总价
    postage: 0, //邮费默认值
    pickUpSelfName: '', // 提货人姓名
    pickUpSelfPhone: '', // 提货人手机
    hasSelectPAmount: 0,
    hasSelectCityPAmount: 0,
    receiverName: '',
    receiverMobile: '',
    receiverAddress: '',
    bottomBtnContent: '确认提交',
    cityCouponNo: '', //市级优惠卷编号
    canCommit: false,
    invitationCode: '',
    remark: '',
    loadingCount: 0, // 记录当前请求的个数，当不为0时，会显示加载提示
    loadingSuccessCount: 0
  },

  onLoad: function (options) {
    const that = this
    if (options.invitationCode) { // 是vip商品填写邀请码
      that.setData({
        invitationCode: that.options.invitationCode
      })
    }
    common.getLocalUserInfo(function (success, data) {
      if (success) {
        that.setData({
          userInfo: data.user,
          token: data.token,
          openid: data.openid,
          itemId: options.itemId,
          storeId: options.storeId,
          pickUpSelfName: data.user.realName,
          pickUpSelfPhone: data.user.phone
        }, function () {
          that.getGoodsDes() //查询商品详情信息
          that.getShopDes() //店铺详情
          if (options.selectedAddr) {
            // 已经选择地址的逻辑，当前逻辑是从选择地址列表返回
            that.setData({
              selectedAddr: options.selectedAddr,
              receiverName: options.receiverName,
              receiverMobile: options.receiverMobile,
              receiverAddress: options.receiverAddress,
            })
          } else {
            // 默认进入 - 未选择地址，从下单页面进入
            getApp().getLocation(function (data) {
              that.data.lon = data.longitude
              that.data.lat = data.latitude
              that.setData({
                xpoint: data.longitude,
                ypoint: data.latitude
              }, function () {
                that.getPostType() //根据位置查询店铺配送方式
              })
            })
          }
        })
      }
    }, true)
  },
  inputEvent(e) { },
  //查询商品详情信息
  getGoodsDes() {
    const that = this
    let tempJson = {
      itemId: that.data.itemId
    }
    that.setData({
      loadingCount: that.data.loadingCount + 1,
      loadingSuccessCount: that.data.loadingSuccessCount - 1
    }, function () {
      common.post('/item/info', tempJson, function (res) {
        if (res.status === 200) {
          that.setData({
            goodsInfo: res.data,
            cityBenefitItemFlag: res.data.cityBenefitItemFlag,
            benefitItemFlag: res.data.benefitItemFlag,
            storePrice: res.data.price,
            price: res.data.price,
            loadingSuccessCount: that.data.loadingSuccessCount + 1
            // totalMoney:
          })
        } else {
          common.showRequestErrMsg(res)
        }
      }, function () {
        that.setData({
          loadingCount: that.data.loadingCount - 1
        })
      })
    })
  },
  //查询店铺信息
  getShopDes() {
    var that = this
    let tempJson = {
      storeId: that.data.storeId
    }
    this.setData({
      loadingCount: this.data.loadingCount + 1,
      loadingSuccessCount: that.data.loadingSuccessCount - 1
    })
    common.post('/store/info', tempJson, function (res) {
      if (res.status === 200) {
        that.setData({
          storeInfo: res.data,
          loadingSuccessCount: that.data.loadingSuccessCount + 1
        })
      } else {
        common.showRequestErrMsg(res)
      }
    }, function () {
      that.setData({
        loadingCount: that.data.loadingCount - 1
      })
    })
  },
  //查询店铺配送方式
  getPostType: function () {
    var that = this
    var tempJson = {
      storeId: that.data.storeId,
      userId: that.data.userInfo.id,
      xpoint: that.data.xpoint,
      ypoint: that.data.ypoint
    }
    this.setData({
      loadingCount: this.data.loadingCount + 1,
      loadingSuccessCount: that.data.loadingSuccessCount - 1
    })
    common.post('/store/getStorePostTypeForBuyUser', tempJson, function (res) {
      if (res.status === 200) {
        that.setData({
          totalPostType: res.data,
          postType: res.data[0].feeType,
          postage: res.data[0].price,
          loadingSuccessCount: that.data.loadingSuccessCount + 1
        }, function () {
          that.selectComponent('#vanTabs').resize()
        })
      } else {
        common.showRequestErrMsg(res)
      }
    }, function () {
      that.setData({
        loadingCount: that.data.loadingCount - 1
      })
    })
  },
  //点击选中的配送方式
  onChangePostType(event) {
    let that = this
    that.setData({
      selectedAddr: false,
      receiverName: '',
      receiverMobile: '',
      receiverAddress: '',
    })
    let feeType = event.detail.name
    that.data.totalPostType.map((item, index) => {
      if (item.feeType == feeType) {
        console.log("yunxing", item.price)
        that.setData({
          postage: item.price,
          postType: item.feeType
        })
      }
    })
  },
  //购买数量  计算数量金额
  onNumChange(e) {
    var that = this;
    var storePrice = parseFloat(that.data.goodsInfo.price) * e.detail
    that.setData({
      count: e.detail,
      storePrice: storePrice
    })
  },
  voucherPayFunc() {
    var that = this
    let payment = that.data.storePrice + that.data.postage - (that.data.hasSelectPAmount || that.data.hasSelectCityPAmount)
    var tempJson = {
      token: that.data.token,
      payType: 0,
      invitationCode: that.data.invitationCode,
      list: [{
        order: {
          payment: payment,
          userId: that.data.userInfo.id,
          postFee: that.data.postage,
          buyerMessage: that.data.remark,
          remark: that.data.remark,
          buyerNick: that.data.userInfo.userName,
          storeId: that.data.storeId,
          postType: that.data.postType, //1—商城配送;2—到店自提
          orderType: 1 //商品订单1，活动订单2
        },
        items: [{
          itemId: that.data.itemId,
          num: that.data.count,
          title: that.data.goodsInfo.title,
          price: that.data.goodsInfo.price,
          totalFee: that.data.count * that.data.goodsInfo.price,
          picPath: that.data.userInfo.image,
        }],
        ship: {
          receiverName: that.data.receiverName || that.data.pickUpSelfName,
          receiverPhone: '', //可以为空
          receiverMobile: that.data.receiverMobile || that.data.pickUpSelfPhone,
          receiverAddress: that.data.receiverAddress,
          receiverZip: ''
        }
      }]
    };
    tempJson.list[0].order.couponNo = that.data.hasSelectPNo
    tempJson.list[0].order.discountMoney = that.data.hasSelectPAmount
    tempJson.list[0].order.payment = tempJson.list[0].order.payment - parseInt(that.data.hasSelectPAmount);

    common.postJson('/order/createBenefitOrder', tempJson, function (ret) {
      console.log("/order/createBenefitOrder接口数据为", ret);
      if (ret.status == 200) {
        console.log('惠民季创建订单跳转到的url为/pages/Goods/benefit/benefitPay/index?payBenefitMoney=' + ret.data[0].order.payment + '&payBenefitOrderNo=' + ret.data[0].order.orderNo + '&payBenefitOrderId=' + ret.data[0].order.id);
        wx.navigateTo({
          url: '/pages/Goods/benefit/benefitPay/index?payBenefitMoney=' + ret.data[0].order.payment + '&payBenefitOrderNo=' + ret.data[0].order.orderNo + '&payBenefitOrderId=' + ret.data[0].order.id + "&fromSmallProgramm=true",
        })
        return;
      } else {
        wx.showToast({
          title: ret.msg,
          icon: 'none'
        })
      }
    })
  },
  normalPayFunc() {
    this.setData({
      loadingCount: this.data.loadingCount + 1
    })
    const that = this
    const payment = that.data.storePrice + that.data.postage - (that.data.hasSelectPAmount || that.data.hasSelectCityPAmount) // 实付金额
    const tempJson = {
      token: that.data.token,
      invitationCode: that.data.invitationCode || '',
      payType: 0,
      list: [{
        order: {
          payment: payment,
          userId: that.data.userInfo.id,
          postFee: that.data.postage,
          buyerMessage: that.data.remark,
          remark: that.data.remark,
          buyerNick: that.data.userInfo.userName,
          storeId: that.data.storeId,
          postType: that.data.postType, //1—商城配送;2—到店自提
          orderType: 1, //商品订单1，活动订单2
          cityCouponNo: that.data.cityCouponNo
        },
        items: [{
          itemId: that.data.itemId,
          num: that.data.count,
          title: that.data.goodsInfo.title,
          price: that.data.goodsInfo.price,
          totalFee: that.data.count * that.data.goodsInfo.price,
          picPath: that.data.goodsInfo.image,
        }],
        ship: {
          receiverName: that.data.receiverName || that.data.pickUpSelfName,
          receiverPhone: '', //可以为空
          receiverMobile: that.data.receiverMobile || that.data.pickUpSelfPhone,
          receiverAddress: that.data.receiverAddress,
          receiverZip: ''
        },
      }]
    };
    common.postJson('/order/create', tempJson, function (ret) {
      if (ret.status == 200) {
        var tempJson = {
          userId: that.data.userInfo.id,
          token: that.data.token,
          orderId: ret.data[0].order.id,
          openid: that.data.openid,
        }
        that.setData({
          loadingCount: that.data.loadingCount + 1
        })
        common.wxPayRequest('/wxxcxPayForGoods', tempJson, function (res) {
          if (res.status !== 200) {
            common.showRequestErrMsg(res)
          } else {
            //微信支付
            wx.requestPayment({
              'timeStamp': res.data.timeStamp,
              'nonceStr': res.data.nonceStr,
              'package': res.data.package,
              'signType': res.data.signType,
              'paySign': res.data.paySign,
              'success': function (res) {
                common.showToast('支付成功', 'success')
                wx.navigateBack({
                  delta: 1
                })
              },
              'fail': function (res) {
                wx.redirectTo({
                  url: '/pages/Goods/goodsOrder/goodsOrderList/index?type=1',
                })
                if (res.errMsg === 'requestPayment:fail cancel') {
                } else {
                  common.showToast(res.errMsg)
                }
              }
            })
          }
        }, function () {
          that.setData({
            loadingCount: that.data.loadingCount - 1
          })
        })
      } else {
        common.showRequestErrMsg(ret)
      }
    }, function () {
      that.setData({
        loadingCount: that.data.loadingCount - 1
      })
    })
  },

  commit: common.throttleFunc(function (e) {
    if (this.data.loadingSuccessCount !== 0) {
      // 存在加载失败的接口，不进行订单提交
      // 全部加载成功loadingSuccessCount值为0
      return
    }
    const that = this
    // 自提方式，验证收货人和手机号
    if (that.data.postType === '2' || that.data.postType === 2) {
      const name = that.data.pickUpSelfName
      if (common.isEmptyString(name)) {
        common.showToast('请输入提货人姓名')
        return
      } else if (common.isEmptyString(that.data.pickUpSelfPhone)) {
        common.showToast('请输入手机号码')
        return
      }
    }

    if (that.data.selectedAddr || that.data.postType == 2) {
      if (that.data.hasSelectPAmount) { // 省级券
        console.log('已选中惠民券');
        that.voucherPayFunc();
      } else { // 没券和市级券
        console.log('不用券||市券');
        that.normalPayFunc();
      }
    } else {
      common.showToast('您还未添加任何地址~')
    }
  }, 2000),
  jumpVoucherList() {
    // console.log('hasSelectPNo', this.data.hasSelectPNo)
    wx.navigateTo({
      url: '/pages/Goods/benefit/benefitVoucher/index?num=' +
        this.data.count + "&itemId=" +
        this.data.itemId +
        // "&hasSelectPNo=" +
        // this.data.hasSelectPNo +
        '&cityBenefitItemFlag=' +
        this.data.cityBenefitItemFlag +
        '&benefitItemFlag=' + this.data.benefitItemFlag
    })
  }
})